var addErpOrderVm = new Vue({
    el: '#addErpOrderApp',
    data: {
        visible: {  // true Or false
            userDialogVisible: false, //客户选择弹出框
            credit: false,///添加订单是否显示可挂账
            quotePriceVisible: false,// 算价价格展示
            productDialogVisible: false,// 添加标品
        },
        query: { // 查询参数
            name: null,//客户姓名
            productName: null,// 产品名
        },
        erpOrder: {
            memberName: '',
            shipName: '',
            orderCreatetime: '',
            tel: '',
            productionStatus: '',
            shipStatus: '',
            productionRequest: ''
        },
        detailData: [],//订单详情table数据:
        sendType: [
            {
                value: '0',
                label: '快递'
            },
            {
                value: '1',
                label: '自提'
            }
        ],// 送货方式
        payTypeData: ["支付宝", "微信", "现金"],//支付方式
        defaultProps: {children: 'children', label: 'label'},
        userInfoData: [],// 客户列表
        salesManList: [], //门店业务员列表
        acceptOrderUserData: [],//接单员列表
        area: [],//地区
        calculatePrice: { // 算价模块
            quoteProductInfo: {}, //报价产品信息
            category: {},// 分类类型
            categoryData: [],//分类数据
            //快印
            fast: {
                categoryData: [],
            },
            // 商务印刷
            print: {
                categoryData: [],
            },
            mustChoiceParts: [],//必选部件
            calculateData: {},// 算价数据
            calculateFormRules: {}, // 算价表单规则
            material: {},//材料属性临时存放
            isShowCraft: {},// 是否显示非必选工艺
            addShowCraft: {},// 是否显示添加工艺
            isShowDefined: {}, //是否显示自定义
            definedArr: {}, //自定义数组
            quotePriceInfoList: [],// 算价结果
            selectedPrice: {},// 选中的算价结果
            salesAmount: 0,// 销售金额
            goodsData: [],// 标品商品数据
        }
    },
    //页面 挂载后 初始化数据
    mounted: function () {
        this.initData();
    },
    methods: {
        initData: function () {
            var date = this.orderCreatetimeFormat();
            this.erpOrder = {
                acceptOrderUser: null, production_request: null, memo: null, productionStatus: null,
                memberName: null, orderSource: null, payStatus: null, shipStatus: null, receivedStatus: null,
                deposit: false, merchantsSalesMan: null, sendType: '1',
                orderCreatetime: date
            };
            //查询接单员列表(pop_sys_user表)以及所有快印以及商务印刷的数据
            var self = this;
            $.get(baseURL + "order/erporder/addData", function (r) {
                if (r.code === 0) {
                    addErpOrderVm.acceptOrderUserData = r.acceptOrderUserData;
                    addErpOrderVm.erpOrder.acceptOrderUser = r.currentUser;
                    addErpOrderVm.area = JSON.parse(r.area);
                    // 赋值算价模块功能
                    addErpOrderVm.calculatePrice.print.categoryData = r.shangWuCategoryData
                    addErpOrderVm.calculatePrice.fast.categoryData = r.fastCategoryData;
                    addErpOrderVm.calculatePrice.categoryData = r.categoryData;
                } else {
                    alert(r.msg);
                }
            });
        },

        //选择客户
        openUserDialog: function () {
            addErpOrderVm.visible.userDialogVisible = true;
            this.$nextTick(function () {
                addErpOrderVm.queryUser();
            })
        },

        //查询用户
        queryUser: function () {
            $.ajax({
                type: "POST",
                url: baseURL + "order/erporder/queryUser",
                data: {"name": addErpOrderVm.query.name},
                success: function (r) {
                    if (r.code == 0) {
                        addErpOrderVm.userInfoData = r.userInfoData
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },

        //双击选中客户，同时关闭弹出框
        selectUser: function (row, event) {
            addErpOrderVm.erpOrder.memberId = row.userId;
            addErpOrderVm.erpOrder.memberName = row.name;
            if (row.tel == '' || row.tel == null) {
                addErpOrderVm.erpOrder.shipTel = row.mobile;
            } else {
                addErpOrderVm.erpOrder.shipTel = row.tel;
            }
            addErpOrderVm.erpOrder.shipAddr = row.address;
            addErpOrderVm.erpOrder.shipName = row.nickname;
            addErpOrderVm.visible.credit = row.hangsAccountCustomer;
            addErpOrderVm.erpOrder.onCredit = row.hangsAccountCustomer;
            //如果有业务员信息，则查出业务员姓名
            if (row.merchantsSalesMan != null) {
                //再根据客户查询对应的业务员
                $.get(baseURL + "order/erporder/getMerchantsSalesMan/" + row.merchantsSalesMan, function (r) {
                    addErpOrderVm.salesManList = r.salesManList;
                    addErpOrderVm.erpOrder.merchantsSalesMan = addErpOrderVm.salesManList[0];
                });
            }
            addErpOrderVm.visible.userDialogVisible = false;
        },

        /*算价方法*/
        //菜单切换
        handleSelect(key, keyPath) {
            //发起请求获取报价模板
            var self = this;
            $.get(baseURL + "order/erporder/getQuoteGoods/" + key, function (r) {
                // 获取菜单类型
                addErpOrderVm.calculatePrice.category = self.$refs.categoryMenu.items[key].$attrs.type;
                //初始化数据
                addErpOrderVm.calculatePrice.calculateFormRules = {};
                addErpOrderVm.calculatePrice.calculateData = {
                    categoryType: '',         //分类
                    attributesMap: {},       // 工艺属性
                    selfPaperParts: {},      // 自来纸
                    definitionValueMap: {},  // 自定义
                    categoryId: key,
                }
                if (r.code == 0) {
                    addErpOrderVm.calculatePrice.quoteProductInfo = r.quoteProductInfo;
                    addErpOrderVm.calculatePrice.calculateData.categoryType = r.quoteProductInfo.categoryType;
                    // 解析数据
                    for (var i = 0; i < addErpOrderVm.calculatePrice.quoteProductInfo.quotePartsList.length; i++) {
                        var temp = addErpOrderVm.calculatePrice.quoteProductInfo.quotePartsList[i];
                        //取出必选部件
                        if (temp.mustChoice == true) {
                            addErpOrderVm.calculatePrice.mustChoiceParts.push(temp.constructId);
                        }
                        //赋值初始值
                        //提交表单属性初始化
                        Vue.set(addErpOrderVm.calculatePrice.calculateData.attributesMap, temp.constructId, {});
                        //提交表单自定义值初始化
                        Vue.set(addErpOrderVm.calculatePrice.calculateData.definitionValueMap, temp.constructId, {});
                        //提交表单自来纸初始化
                        Vue.set(addErpOrderVm.calculatePrice.calculateData.selfPaperParts, temp.constructId, false);
                        //临时材料初始化
                        Vue.set(addErpOrderVm.calculatePrice.material, temp.constructId, {});
                        //临时 是否展示自定义 初始化
                        Vue.set(addErpOrderVm.calculatePrice.isShowDefined, temp.constructId, {});
                        //临时 自定义数组 初始化
                        Vue.set(addErpOrderVm.calculatePrice.definedArr, temp.constructId, {});
                        //临时 是否展示自定义按钮初始化
                        Vue.set(addErpOrderVm.calculatePrice.addShowCraft, temp.constructId, false);
                        //赋值默认选项
                        //循环 quoteAttributeOptionList
                        for (var quoteAttribute of temp.quoteAttributeList) {
                            if (quoteAttribute.canDefinition === true) {
                                Vue.set(addErpOrderVm.calculatePrice.calculateData.definitionValueMap[temp.constructId], quoteAttribute.attributeTypeValue, {});
                            }

                            for (var quoteOption of quoteAttribute.quoteAttributeOptionList) {
                                // 普通属性默认值
                                if (quoteAttribute.attributeType === 'normal' && quoteOption.defaultOption === true) {
                                    Vue.set(addErpOrderVm.calculatePrice.calculateData.attributesMap[quoteAttribute.constructId], quoteAttribute.attributeTypeValue, quoteOption.id);
                                    //break loopOption;
                                }
                                // 必选工艺 赋默认值
                                if (quoteAttribute.attributeType === 'craft' && quoteAttribute.mustChioce === true && quoteOption.defaultOption === true) {
                                    Vue.set(addErpOrderVm.calculatePrice.calculateData.attributesMap[quoteAttribute.constructId], quoteAttribute.attributeTypeValue, quoteOption.id);
                                }
                                // 非必选工艺
                                if (quoteAttribute.attributeType === 'craft' && quoteAttribute.mustChioce != true) {
                                    Vue.set(addErpOrderVm.calculatePrice.isShowCraft, temp.constructId, true);
                                }

                                // 材料特殊处理  寻找克重
                                if (quoteAttribute.attributeType === 'material' && quoteOption.defaultOption === true) {
                                    // 先赋值材料
                                    Vue.set(addErpOrderVm.calculatePrice.material[quoteAttribute.constructId], 'defaultOption', quoteOption.optionKey);
                                    Vue.set(addErpOrderVm.calculatePrice.material[quoteAttribute.constructId], 'sonOptionList', quoteOption.sonOptionList);
                                    // 循环当前克重 找出默认克重
                                    loopSonOption:
                                        for (var sonOption of quoteOption.sonOptionList) {
                                            if (sonOption.defaultOption === true) {
                                                Vue.set(addErpOrderVm.calculatePrice.calculateData.attributesMap[quoteAttribute.constructId], quoteAttribute.attributeTypeValue, sonOption.id);
                                                break loopSonOption;
                                            }
                                        }
                                }

                            }
                            //生成表单校验规则
                            if (quoteAttribute.mustChioce === true) {
                                var rule = {required: true, message: '请选择' + quoteAttribute.name, trigger: 'change'};
                                Vue.set(addErpOrderVm.calculatePrice.calculateFormRules, 'attributesMap.' + temp.constructId + '.' + quoteAttribute.attributeTypeValue, rule);
                            }
                        }
                    }
                } else {
                    alert(r.msg);
                }
            });
        },

        //分类被点击触发事件,查找当前分类下的材料
        handleNodeClick(data) {
            var  categoryId = data.categoryId;
            $.get(baseURL + "order/erporder/productInfo/"+categoryId, function(r){
                addErpOrderVm.calculatePrice.goodsData = r.goodsData;
            });
        },

        //产品搜索
        productSearch: function () {
            $.ajax({
                type: "POST",
                url: baseURL + "order/erporder/productSearch",
                contentType: "application/x-www-form-urlencoded",
                dataType: "json",
                data: {"productName": addErpOrderVm.query.productName},
                success: function (r) {
                    if (r.code == 0) {
                        addErpOrderVm.calculatePrice.goodsData = r.goodsData
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },

        /* 材料切换,克重置为空 */
        materialChange: function (optionKey, constructId, optionList) {
            //重置 克重下拉框option
            var option = optionList.filter(function (option) {
                return option.optionKey === optionKey;
            });
            if (option.length == 1) {
                addErpOrderVm.calculatePrice.material[constructId].sonOptionList = option[0].sonOptionList;
            } else if (option.length == 0) {
                addErpOrderVm.calculatePrice.material[constructId].sonOptionList = null;
            }
            // 清空克重
            var material = addErpOrderVm.calculatePrice.calculateData.attributesMap[constructId].material;
            if (material) {
                addErpOrderVm.calculatePrice.calculateData.attributesMap[constructId].material = null;
            }
        },

        /*自定义切换*/
        defineChange: function (constructId, quoteAttribute, value) {
            if (value == false) { //取消自定义
                //清除 自定义规则
                for (var i = 0; i < addErpOrderVm.calculatePrice.definedArr[constructId][quoteAttribute.attributeTypeValue].length; i++) {
                    Vue.set(addErpOrderVm.calculatePrice.calculateData.definitionValueMap[constructId][quoteAttribute.attributeTypeValue], i, null);
                    Vue.set(addErpOrderVm.calculatePrice.calculateFormRules, 'definitionValueMap.' + constructId + '.' + quoteAttribute.attributeTypeValue + '.' + i, null);
                }
                Vue.delete(addErpOrderVm.calculatePrice.calculateData.definitionValueMap[constructId].quoteAttribute.attributeTypeValue, {});
                Vue.delete(addErpOrderVm.calculatePrice.definedArr[constructId], quoteAttribute.attributeTypeValue);
                return;
            }
            //先查找当前选项id
            var optionId = addErpOrderVm.calculatePrice.calculateData.attributesMap[constructId][quoteAttribute.attributeTypeValue];
            // 查找当前选项
            var option = $.grep(quoteAttribute.quoteAttributeOptionList, function (temp) {
                return temp.id === optionId;
            });
            if (option.length == 0) {
                this.$message({showClose: true, message: '请先选择选项 !', type: 'warning'});
                return;
            }
            if (option.length > 1) {
                this.$message({showClose: true, message: '选项数据异常，请联系管理员 !', type: 'error'});
                return;
            }
            //判断当前选项是否有 自定义
            var arrTemp = [];
            if (option.canDefinition === true) {
                // 解析自定义选项
                arrTemp = JSON.parse(option.definitionLength);

            } else {
                // 取属性自定义
                if (quoteAttribute.canDefinition === true) {
                    arrTemp = JSON.parse(quoteAttribute.definitionLength);
                }
            }

            if (arrTemp.length > 0) {
                // 赋值自定义数据
                Vue.set(addErpOrderVm.calculatePrice.definedArr[constructId], quoteAttribute.attributeTypeValue, arrTemp);

                // 动态绑定数组值
                Vue.set(addErpOrderVm.calculatePrice.calculateData.definitionValueMap[constructId], quoteAttribute.attributeTypeValue, {});
                for (var i = 0; i < arrTemp.length; i++) {
                    Vue.set(addErpOrderVm.calculatePrice.calculateData.definitionValueMap[constructId][quoteAttribute.attributeTypeValue], i, null);
                    // 赋值表单校验
                    var rule = {
                        required: true,
                        type: 'number',
                        min: arrTemp[i][0],
                        max: arrTemp[i][1],
                        message: arrTemp[i][0] + '-' + arrTemp[i][1] + ' ',
                        trigger: 'blur'
                    }
                    Vue.set(addErpOrderVm.calculatePrice.calculateFormRules, 'definitionValueMap.' + constructId + '.' + quoteAttribute.attributeTypeValue + '.' + i, rule);
                }
            }
        },

        /*提交表单计算价格*/
        submitForm: function (formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    var url = '';
                    if (addErpOrderVm.calculatePrice.category === 'fast') {
                        url = "order/erporder/fastCaculateQuote";
                    } else if (addErpOrderVm.calculatePrice.category === 'print') {
                        url = "order/erporder/caculateQuote";
                    } else {
                        alert("数据异常,请刷新页面!");
                        return;
                    }

                    $.ajax({
                        type: "POST",
                        url: baseURL + url,
                        contentType: "application/json",
                        data: JSON.stringify(addErpOrderVm.calculatePrice.calculateData),
                        success: function (r) {
                            if (r.code == 0) {
                                if (addErpOrderVm.calculatePrice.category === 'fast') {
                                    addErpOrderVm.calculatePrice.quotePriceInfoList = r.fastFactoryQuoteInfoList;
                                    //默认第一个选中
                                    addErpOrderVm.calculatePrice.selectedPrice = r.fastFactoryQuoteInfoList[0];
                                    addErpOrderVm.visible.quotePriceVisible = true;
                                } else if (addErpOrderVm.calculatePrice.category === 'print') {
                                    addErpOrderVm.calculatePrice.quotePriceInfoList = r.factoryQuoteInfoList;
                                    // 默认第三个选中
                                    addErpOrderVm.calculatePrice.selectedPrice = r.factoryQuoteInfoList[2];
                                    addErpOrderVm.visible.quotePriceVisible = true;
                                }
                            } else {
                                alert(r.msg);
                            }
                        }
                    });
                } else {
                    this.$message.error('请按页面提示修改参数!');
                    return false;
                }
            });
        },

        /*添加选中价格到订单详情*/
        addCalculatePrice: function () {
            var goods = {};
            goods.productId = addErpOrderVm.calculatePrice.selectedPrice.productId;
            goods.productName = addErpOrderVm.calculatePrice.selectedPrice.productName;
            goods.quantity = addErpOrderVm.calculatePrice.selectedPrice.quantity;
            goods.price = addErpOrderVm.calculatePrice.selectedPrice.unitPrice;
            goods.total = addErpOrderVm.calculatePrice.selectedPrice.totalPrice;
            goods.goodsType = addErpOrderVm.calculatePrice.category; // 类型
            goods.craft = addErpOrderVm.calculatePrice.selectedPrice.addon;
            goods.calculationPriceProcess = addErpOrderVm.calculatePrice.selectedPrice.priceProcess;
            goods.productInfoParamList = addErpOrderVm.calculatePrice.selectedPrice.productInfoParamList;
            goods.attributeOption = addErpOrderVm.calculatePrice.selectedPrice.attributeOption;
            goods.quoteSelfDefineParam = addErpOrderVm.calculatePrice.selectedPrice.quoteSelfDefineParam;
            goods.cutModel = addErpOrderVm.calculatePrice.selectedPrice.cutModel;
            goods.cutModelObj = JSON.parse(goods.cutModel);

            //如果输入了金额，对总价重新计算
            if (addErpOrderVm.calculatePrice.salesAmount != 0) {
                goods.total = addErpOrderVm.calculatePrice.salesAmount;
                goods.price = (goods.total / goods.total.quantity).toFixed(3);
            }
            addErpOrderVm.detailData.push(goods);
            addErpOrderVm.visible.quotePriceVisible = false;
            //清空选择和输入的数据
            addErpOrderVm.calculatePrice.salesAmount = 0;
            addErpOrderVm.calculatePrice.selectedPrice = {};

        },

        //删除订单详情中的商品
        deleteGoods:function (index) {
            addErpOrderVm.detailData.splice(index,1);
        },


        saveOrUpdate: function () {
            this.$refs["addErpOrderForm"].validate((valid)=>{
                if (valid){
                    var url = "order/erporder/save";
                    //先拼接参数
                    var erpOrderItemDto = {};
                    erpOrderItemDto.erpOrder = addErpOrderVm.erpOrder;
                    erpOrderItemDto.storeGoodsProductList = addErpOrderVm.detailData;
                    if (addErpOrderVm.detailData.length == 0){
                        alert("请至少选择一种产品！")
                        return;
                    }
                    // 异步提交
                    $.ajax({
                        type: "POST",
                        url: baseURL + url,
                        contentType: "application/json",
                        data: JSON.stringify(erpOrderItemDto),
                        success: function(r){
                            if(r.code === 0){
                                alert('添加成功', function(index){
                                    //vm.reload();
                                });
                            }else{
                                alert(r.msg);
                            }
                        }
                    });
                }else {
                    this.$message.error('请按页面提示修改参数!');
                    return false;
                }
            });
        },

        /*工具类*/

        // 省市区
        handleItemChange: function (val) {
            var values = val.join(',').split(',');
            var lableVal = addErpOrderVm.getCascaderObj(val, addErpOrderVm.area);
            var area = lableVal.join(',').replace(new RegExp(',', 'g'), ' ');
            addErpOrderVm.erpOrder.shipArea = area;
        },

        //格式化date_time-picker数据
        orderCreatetimeFormat() {
            let date = new Date();
            let Y = date.getFullYear();
            let M = date.getMonth() + 1
            M = (M < 10 ? '0' + M : M);
            let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
            let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
            let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
            let s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
            return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s
        },

        getCascaderObj(val, opt) {
            return val.map(function (value, index, array) {
                for (var itm in opt) {
                    if (opt[itm].value == value) {
                        var label = opt[itm].label;
                        opt = opt[itm].children;
                        return label;
                    }
                }
                return null;
            });
        },

    },
});